//
//  LoginViewController.m
//  yunyan
//
//  Created by haichuang on 2018/2/11.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "MainTabBarController.h"
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *accountTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UIImageView *wxImage;
@property (weak, nonatomic) IBOutlet UIImageView *qqImage;

@property (weak, nonatomic) IBOutlet UIImageView *wbImage;

@end
@implementation LoginViewController


-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    self.accountTF.text = USER_DEFAULTGet(@"mobile");
    
    [self.wxImage tapAction:^{
        
         [self login:SSDKPlatformTypeWechat with:1];
    }];
    [self.qqImage tapAction:^{
        
         [self login:SSDKPlatformTypeQQ with:2];
    }];
    
    [self.wbImage tapAction:^{
        
        [self login:SSDKPlatformTypeSinaWeibo with:3];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//忘记密码

- (IBAction)forgetPassword:(UIButton *)sender {
    
    RegisterViewController * registerVC = [[RegisterViewController alloc]init];
    registerVC.isRegister = NO;
    registerVC.isLogin = YES;
    [self.navigationController pushViewController:registerVC animated:YES];
    
}
//注册
- (IBAction)registerBtn:(UIButton *)sender {
    
    RegisterViewController * registerVC = [[RegisterViewController alloc]init];
    registerVC.isRegister = YES;
     registerVC.isLogin = YES;
     registerVC.isPhone = YES;
    [self.navigationController pushViewController:registerVC animated:YES];
}


- (IBAction)backBtnClick:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//登录
- (IBAction)loginBtn:(UIButton *)sender {
    if (self.accountTF.text==nil||self.accountTF.text.length
        !=11) {
        
        SHuiMBhudTextTimeStr(@"请输入正确的手机号");
        return;
    }
    if (self.passwordTF.text==nil||self.passwordTF.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入密码");
        return;
    }
    if (self.passwordTF.text.length<6) {
        
        SHuiMBhudTextTimeStr(@"密码长度不能小于6");
        return;
    }
    [self phoneLogingRequest];
    
//    MainTabBarController * root = [[MainTabBarController alloc]init];
//    [UIApplication sharedApplication].keyWindow.rootViewController = root;
}
//微信登录
- (IBAction)weixinLogin:(UIButton *)sender {
//    MainTabBarController * root = [[MainTabBarController alloc]init];
//    [UIApplication sharedApplication].keyWindow.rootViewController = root;
    
//    [self login:SSDKPlatformTypeWechat with:1];
}
// QQ登录
- (IBAction)QQLogin:(UIButton *)sender {
//    MainTabBarController * root = [[MainTabBarController alloc]init];
//    [UIApplication sharedApplication].keyWindow.rootViewController = root;
    
//     [self login:SSDKPlatformTypeQQ with:2];
}
//- (IBAction)wx:(id)sender {
//
//      [self login:SSDKPlatformTypeWechat with:1];
//}
//- (IBAction)qq:(id)sender {
//    
//    [self login:SSDKPlatformTypeQQ with:2];
//    
////    [self thirdQQLoging];
//}

-(void)login:(SSDKPlatformType )type with:(int)index{
    
    
    [SSEThirdPartyLoginHelper loginByPlatform:type onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
        associateHandler (user.uid, user, user);
        
        NSString *strUrl = RequestUrlStr(third_verifyLoging_api);
        NSDictionary *dic;
        NSString * signMd5;
        if (index==1) {
         
           
               signMd5 = [SHJudgeTools md532BitLower:[NSString stringWithFormat:@"%@%@%@%@%@zyWf*y3vIjYxvRfH",[SHJudgeTools getDeviceId],@"161",user.credential.rawData[@"openid"],user.credential.rawData[@"access_token"],user.credential.rawData[@"unionid"]]];
            
            dic = @{@"access_token":user.credential.rawData[@"access_token"],
                    @"mac_code":[SHJudgeTools getDeviceId],
                    @"login_type":@"161",
                    @"unionid":user.credential.rawData[@"unionid"],
                    @"client":@"200",
                    @"openid":user.credential.rawData[@"openid"],
                    @"sign":signMd5
                    };
            
            USER_DEFAULTSet(@"161", @"login_type");
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"openid"] forKey:@"openid"];
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"access_token"] forKey:@"access_token"];
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"unionid"] forKey:@"unionid"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else if(index==2){
            signMd5 = [SHJudgeTools md532BitLower:[NSString stringWithFormat:@"%@%@%@%@%@zyWf*y3vIjYxvRfH",[SHJudgeTools getDeviceId],@"163",user.credential.rawData[@"openid"],user.credential.rawData[@"access_token"],user.credential.rawData[@"openid"]]];
            dic = @{@"access_token":user.credential.rawData[@"access_token"],
                    @"mac_code":[SHJudgeTools getDeviceId],
                    @"login_type":@"163",
                    @"unionid":user.credential.rawData[@"openid"],
                    @"client":@"200",
                    @"openid":user.credential.rawData[@"openid"],
                    @"sign":signMd5
                    };
            
             USER_DEFAULTSet(@"163", @"login_type");
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"openid"] forKey:@"openid"];
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"access_token"] forKey:@"access_token"];
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"openid"] forKey:@"unionid"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else {
            
            signMd5 = [SHJudgeTools md532BitLower:[NSString stringWithFormat:@"%@%@%@%@%@zyWf*y3vIjYxvRfH",[SHJudgeTools getDeviceId],@"163",user.credential.rawData[@"uid"],user.credential.rawData[@"access_token"],user.credential.rawData[@"uid"]]];
            dic = @{@"access_token":user.credential.rawData[@"access_token"],
                    @"mac_code":[SHJudgeTools getDeviceId],
                    @"login_type":@"162",
                    @"unionid":user.credential.rawData[@"uid"],
                    @"client":@"200",
                    @"openid":user.credential.rawData[@"uid"],
                    @"sign":signMd5
                    };
            
            USER_DEFAULTSet(@"162", @"login_type");
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"uid"] forKey:@"openid"];
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"access_token"] forKey:@"access_token"];
            [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"uid"] forKey:@"unionid"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }
        
        [PostNetWorking postNetWorkingStr:strUrl andparameters:dic Success:^(id responseObject) {
            
            SHuiMBhudTextTimeStr(@"登录成功");
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                
                USER_DEFAULTSet(responseObject[@"info"][@"user_id"], @"user_id");
                USER_DEFAULTSet(responseObject[@"info"][@"user_nick"], @"user_nick");
                USER_DEFAULTSet(responseObject[@"info"][@"mobile"], @"mobile");
                USER_DEFAULTSet(responseObject[@"info"][@"head_url"], @"head_url");
                USER_DEFAULTSet(responseObject[@"info"][@"birthday"], @"birthday");
                USER_DEFAULTSet(responseObject[@"info"][@"user_sex"], @"user_sex");
                USER_DEFAULTSet(responseObject[@"token"], @"token");
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    
//                    MainTabBarController * root = [[MainTabBarController alloc]init];
//                    [UIApplication sharedApplication].keyWindow.rootViewController = root;
                    [self dismissViewControllerAnimated:YES completion:^{

                    }];
                });
            });
            
        } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            
            RegisterViewController * registerVC = [[RegisterViewController alloc]init];
            registerVC.isRegister = YES;
            registerVC.isLogin = YES;
            registerVC.isPhone = NO;
            [self.navigationController pushViewController:registerVC animated:YES];
            
        }];

        NSLog(@"授权成功 dic = %@",dic);
        
    } onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
        
        if (state == SSDKResponseStateSuccess)
        {
//            SHuiMBhudTextTimeStr(@"授权成功");
        }
        
    }];
 
}

-(void)thirdQQLoging{
    
    [ShareSDK getUserInfo:SSDKPlatformTypeQQ
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             
             NSString *strUrl = RequestUrlStr(third_verifyLoging_api);
             NSLog(@"uid=%@",user.uid);
             NSLog(@"%@",user.credential);
             NSLog(@"token=%@",user.credential.token);
             NSLog(@"nickname=%@",user.nickname);
             NSLog(@"unionid--%@",[user.credential rawData][@"unionid"]);
             
          NSString *   signMd5 = [SHJudgeTools md532BitLower:[NSString stringWithFormat:@"%@%@%@%@%@zyWf*y3vIjYxvRfH",[SHJudgeTools getDeviceId],@"163",user.credential.rawData[@"openid"],user.credential.rawData[@"access_token"],user.credential.rawData[@"unionid"]]];
           NSDictionary *  dic = @{@"access_token":user.credential.rawData[@"access_token"],
                     @"mac_code":[SHJudgeTools getDeviceId],
                     @"login_type":@"163",
                     @"unionid":user.credential.rawData[@"unionid"],
                     @"client":@"200",
                     @"openid":user.credential.rawData[@"openid"],
                     @"sign":signMd5
                     };
             
             USER_DEFAULTSet(@"163", @"login_type");
             [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"openid"] forKey:@"openid"];
             [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"access_token"] forKey:@"access_token"];
             [[NSUserDefaults standardUserDefaults] setObject:user.credential.rawData[@"unionid"] forKey:@"unionid"];
             [[NSUserDefaults standardUserDefaults] synchronize];
         
         [PostNetWorking postNetWorkingStr:strUrl andparameters:dic Success:^(id responseObject) {
             
             SHuiMBhudTextTimeStr(@"登录成功");
             dispatch_async(dispatch_get_global_queue(0, 0), ^{
                 
                 
                 USER_DEFAULTSet(responseObject[@"info"][@"user_id"], @"user_id");
                 USER_DEFAULTSet(responseObject[@"info"][@"user_nick"], @"user_nick");
                 USER_DEFAULTSet(responseObject[@"info"][@"mobile"], @"mobile");
                 USER_DEFAULTSet(responseObject[@"info"][@"head_url"], @"head_url");
                 USER_DEFAULTSet(responseObject[@"info"][@"birthday"], @"birthday");
                 USER_DEFAULTSet(responseObject[@"info"][@"user_sex"], @"user_sex");
                 USER_DEFAULTSet(responseObject[@"token"], @"token");
                 
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                     [self dismissViewControllerAnimated:YES completion:^{
                         
                         //15982296420   15902692249
                     }];
//                     MainTabBarController * root = [[MainTabBarController alloc]init];
//                     [UIApplication sharedApplication].keyWindow.rootViewController = root;
                 });
             });
             
         } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
             
             RegisterViewController * registerVC = [[RegisterViewController alloc]init];
             registerVC.isRegister = YES;
             registerVC.isLogin = YES;
             registerVC.isPhone = NO;
             [self.navigationController pushViewController:registerVC animated:YES];
             
         }];
             
             
             
         } else
         {
             NSLog(@"%@",error);
         }
         
     }];
    
    
}


-(void)phoneLogingRequest{
    
     NSString * signMd5 = [SHJudgeTools md532BitLower:[NSString stringWithFormat:@"%@%@%@zyWf*y3vIjYxvRfH",[SHJudgeTools getDeviceId],self.accountTF.text,self.passwordTF.text]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,loging_phone_api];
    NSDictionary * parameter = @{@"mobile":self.accountTF.text,
                                 @"password":self.passwordTF.text,
                                 @"client":@"200",
                                 @"sign":signMd5,
                                 @"login_type":@"160",
                                 @"mac_code":[SHJudgeTools getDeviceId]
                                 };
    
    SHuiMBhubNoTimeStr(@"正在登录");
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^( id  responseObject) {
        SHuiMBHidleYes;
     
            SHuiMBhudTextTimeStr(@"登录成功");
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                
                USER_DEFAULTSet(responseObject[@"info"][@"user_id"], @"user_id");
            USER_DEFAULTSet(responseObject[@"info"][@"user_nick"], @"user_nick");
                USER_DEFAULTSet(responseObject[@"info"][@"mobile"], @"mobile");
                USER_DEFAULTSet(responseObject[@"info"][@"head_url"], @"head_url");
                 USER_DEFAULTSet(responseObject[@"info"][@"birthday"], @"birthday");
                 USER_DEFAULTSet(responseObject[@"info"][@"user_sex"], @"user_sex");
                USER_DEFAULTSet(responseObject[@"token"], @"token");
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                    
//                    MainTabBarController * root = [[MainTabBarController alloc]init];
//                    [UIApplication sharedApplication].keyWindow.rootViewController = root;
                });
            });
            
      
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        SHuiMBHidleYes;
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"密码或者账号不正确");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

@end
